<template>
  <div v-loading="loading" class="documents-edit">
    <div class="menu">
      <el-tree
        ref="tree"
        :data="treeData"
        :props="defaultProps"
        highlight-current
        :indent="10"
        node-key="id"
      >
        <span slot-scope="{ node, data }" class="tree-node">
          <div class="rows">
            <span class="titTree">
              <i v-if="data.type === 'folder'" class="el-icon-fold" />
              <i v-if="keyWordTypeList.includes(data.type)" class="el-icon-word-key" />
              <el-popover
                v-if="data.type === 'column'"
                placement="right"
                width="100"
                trigger="hover"
                popper-class="body"
              >
                <p>请选择插入的类型</p>
                <div style="text-align: left;">
                  <el-button style="margin-bottom: 5px;margin-left: 0px;" type="primary" size="mini" @click="insertKey(data,'obj')">关键字</el-button>
                  <el-button style="margin-bottom: 5px;margin-left: 0px;" type="primary" size="mini" @click="insertKey(data,'sections')">循环行字段</el-button>
                  <el-button style="margin-left: 0px;" type="primary" size="mini" @click="insertKey(data,'table')">表格字段</el-button>
                </div>
                <p slot="reference">{{ $t(node.label) }}</p>
              </el-popover>
              <p v-else>{{ $t(node.label) }}</p>
            </span>
            <span v-if="keyWordTypeList.includes(data.type)" class="more" style="display: block">
              <el-dropdown>
                <span class="el-dropdown-link">
                  <i class="el-icon-more" style="transform: rotate(90deg)" />
                </span>
                <el-dropdown-menu slot="dropdown" class="dropdown-more">
                  <a class="center" @click="insertLabel(data, 'sections')">
                    <el-dropdown-item>循环块</el-dropdown-item>
                  </a>
                  <a class="center" @click="insertLabel(data, 'table')">
                    <el-dropdown-item>表格表头</el-dropdown-item>
                  </a>
                </el-dropdown-menu>
              </el-dropdown>
            </span>
          </div>
        </span>
      </el-tree>
    </div>
    <div id="documents" class="documents">
      <!-- <div id="placeholder" class="placeholder" /> -->
    </div>
  </div>
</template>

<script>
import {
onlineEditTemplate
} from '@/api/system/word/template/wordOnlineTemplate.js'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      visible: false,
      loading: false,
      editParam: {},
      jsFlag: false,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'keyWord'
      },
      keyWordTypeList: ['single', 'multivalued', 'image']
    }
  },
  watch: {
  },
  mounted() {
  },
  created() {
  },
  methods: {
     init(fileId) {
      this.loading = true
      this.initDiv()
       onlineEditTemplate({ fileId: fileId, authorization: getToken() }).then(async response => {
          if (response.data) {
            this.editParam = response.data
            this.treeData = response.data.keyWordList
            // await this.initAppJs(response.data.scriptFile)
            this.initEditor(
            'edit',
            '',
            { 'edit': true, 'review': true })
          }
          this.loading = false
      })
    },
    initDiv() {
      // 创建office div
      var placeholderDiv = document.getElementById('documents')
      placeholderDiv.innerHTML = ''
      placeholderDiv.innerHTML = '<div id="placeholder" class="placeholder" />'
    },
    initAppJs(scriptFile) {
      const script = document.createElement('script')
      script.src = scriptFile
      // script.async = true
      script.type = 'text/javascript'
      document.head.appendChild(script)
      this.jsFlag = true
    },
    initEditor(mode, type, permission) {
      // mode for editor
      window.mode = window.mode || mode || 'view'
      mode = window.mode

      // mode for editor
      window.type = window.type || type || 'desktop'
      type = window.type

      // url for document
      // window.docUrl = document.getElementById("documentUrl").value;
      var docUrl = this.editParam.fileDownloadUrl
      window.docUrl = this.editParam.fileDownloadUrl
      // key for chaching and collaborate editing
      window.docKey = this.editParam.docKey

      // type for document
      var docType = docUrl.substring(docUrl.lastIndexOf('.') + 1).trim().toLowerCase()

      // type for editor
      var documentType = this.getDocumentType(docType)

      window.permission = window.permission || permission || { 'comment': true, 'download': true, 'edit': true, 'fillForms': true, 'print': true, 'review': false }
      window.user = this.editParam.user.nickName

      window.user = window.user || '测试'
      var id = window.user + '-4'

      // 编辑器加载完成时回调事件
      var onAppReady = function() {
        console.log('编辑器加载完成')
      }
      // 文档加载完成时回调事件
      var onDocumentReady = function(event) {
        console.log('文档已加载完成')
        getCtctrlTree()
        console.log(event)
      }
      // 文档修改时回调事件
      var onDocumentStateChange = function(event) {
        if (event.data) {
          console.log('文档已修改')
          getCtctrlTree()
        }
      }
      // 文档修改时回调事件
      var onError = function(event) {
        if (event.data) {
          console.log('文档已修改')
        }
      }
      var onGetDocumentContent = function(event) {
        console.log('eventtt', event)
        var data = event.data
        console.log(data, 'nnnnn')
        window.ctctrlData = event.data
      }
      // 如果编辑器之外的页面有获取焦点的操作，需要添加此事件，事件写法固定
      var onResetFocus = function() {
        console.log('onResetFocus')
        var active = document.activeElement
        console.log('active', active)
        document.activeElement.blur() // 编辑器外失去焦点
      }
      var onDistPartAuth = function(event) { // 修改权限触发事件，返回相关参数
        console.log('onDistPartAuth: ', event)
      }
      var getCtctrlTree = function() {
        var expression = {
          object: 'content',
          type: 'contentControlChildren'
        }
        docEditor.getDocumentContent(expression)
      }
      // eslint-disable-next-line no-undef
      var docEditor = window.docEditor = new CXO_API.CXEditor('placeholder', {
        type: type,
        width: (type === 'desktop' ? '100%' : undefined),
        height: (type === 'desktop' ? '100%' : undefined),
        documentType: documentType,
        // token: 'eyJ0eXBlIjoiMSIsImFsZyI6IkhTNTEyIn0.e30.RgxbmTaMyvL4cYnOg2DH03JghyUeIlLTiFDZrxqM4Ai_8XGv0K1qw0DB2r9EDRmiLb9ROxzzg36J62V-2IvaXA',
        document: {
          title: this.editParam.fileName,
          usePdfjs: true,
          url: docUrl,
          fileType: docType,
          key: this.editParam.docKey,
          permissions: window.permission
        },
        editorConfig: {
          callbackUrl: this.editParam.localhost + this.editParam.contextPath + '/onlinePreview/callbackUrl?id=' + this.editParam.docKey + '&Authorization=' + this.editParam.Authorization,
          // limitEditMode:"distri",
          mode: mode,
          user: {
            'id': id,
            'name': window.user
          },
          customization: {
            // reviewDisplay:"original",
            about: true,
            chat: false,
            comments: false,
            zoom: 100,
            leftMenu: true,
            rightMenu: false,
            toolbar: true,
            displayTitle: true,
            header: true,
            statusBar: true,
            autosave: true,
            forcesave: true
          }
        },
        events: {
          'onDocumentReady': onDocumentReady,
          'onAppReady': onAppReady,
          'onGetDocumentContent': onGetDocumentContent,
          'onDocumentStateChange': onDocumentStateChange,
          'onResetFocus': onResetFocus,
          'onDistPartAuth': onDistPartAuth,
          'onTypeDataChangeEvent': onDocumentStateChange,
          'onError': onError
        }
      })
    },
    getDocumentType(ext) {
      if ('.doc.docx.docm.dot.dotx.dotm.odt.fodt.ott.rtf.txt.html.htm.mht.pdf.djvu.fb2.epub.xps'.indexOf(ext) !== -1) return 'text'
      if ('.xls.xlsx.xlsm.xlt.xltx.xltm.ods.fods.ots.csv'.indexOf(ext) !== -1) return 'spreadsheet'
      if ('.pps.ppsx.ppsm.ppt.pptx.pptm.pot.potx.potm.odp.fodp.otp'.indexOf(ext) !== -1) return 'presentation'
      return null
    },
    insertKey(data, type) {
      data.visible = false
      if (data.type === 'column') {
        if (type === 'obj') {
            this.insertKeyByParam('${' + data.keyCode + '.' + data.codeFlag + '}')
        } else if (type === 'sections') {
            this.insertKeyByParam('${' + data.codeFlag + '}')
        } else if (type === 'table') {
            this.insertKeyByParam('[' + data.codeFlag + ']')
        }
      }
    },
    insertLabel(data, type) {
      if (type === 'sections') {
        this.insertKeyByParam('${?' + data.codeFlag + '}${/' + data.codeFlag + '}')
      } else if (type === 'table') {
        this.insertKeyByParam('${' + data.codeFlag + '}')
      }
    },
    insertKeyByParam(keyWord) {
      const textObj = {
                'object': 'text', // 表示是文字，必填项
                'type': 'insert', // 表示是插入操作必填项
                'text': keyWord // 插入的文字内容，必填项
            }
      window.docEditor.setDocumentContent(textObj)
    }
  }
}
</script>
<style lang="scss" scoped>
.documents-edit{
  height: 100%;
  display: flex;
  .menu{
    width: 230px;
    min-width: 230px;
    height: 100%;
    overflow: auto;
    padding: 10px;
    /deep/.el-tree {
      font-size: 14px;
      color: #606266;
      .el-tree-node__content {
        height: 36px!important;
      }
      .tree-node{
        width: 100%;
        height: 35px;
        padding: 0;
        .rows{
          display: flex;
          align-items: center;
          height: 100%;
          .titTree{
            display: flex;
            align-items: center;
            font-size: 12px;
            flex: 1;
            overflow: hidden;
            height: 100%;
            i{
              width: 17px;
            }
            p{
              margin: 0;
              display: inline-block;
            }
            span{
              height: 100%;
              width: 100%;
              display: inline-block;
              p{
                height: 100%;
                width: 100%;
                line-height: 35px;
              }
            }
          }
        }
      }
    }
  }
  .documents {
    height: calc(100% - 1px);
    flex: 1;
    width: calc(100% - 231px);
    max-width: calc(100% - 231px);
  }
  .mb-5 {
    margin-bottom: 5px;
  }
}
</style>
